<?php



define('IN_OS', true);

require(dirname(__FILE__) . '/includes/init.php');

if ((DEBUG_MODE & 2) != 2)
{
    $smarty->caching = true;
}

$affiliate = unserialize($GLOBALS['_CFG']['affiliate']);
$smarty->assign('affiliate', $affiliate);

/*------------------------------------------------------ */
//-- INPUT
/*------------------------------------------------------ */

$goods_id = isset($_REQUEST['id'])  ? intval($_REQUEST['id']) : 0;
$color_id = isset($_REQUEST['color_id'])  ? intval($_REQUEST['color_id']) : 0;

/*------------------------------------------------------ */
//-- 改变属性、数量时重新计算商品价格
/*------------------------------------------------------ */

if (!empty($_REQUEST['act']) && $_REQUEST['act'] == 'price')
{
    include('includes/cls_json.php');

    $json   = new JSON;
    $res    = array('err_msg' => '', 'result' => '', 'qty' => 1);

    $attr_id    = isset($_REQUEST['attr']) ? explode(',', $_REQUEST['attr']) : array();
    $number     = (isset($_REQUEST['number'])) ? intval($_REQUEST['number']) : 1;

    if ($goods_id == 0)
    {
        $res['err_msg'] = '没有找到指定的商品或者没有找到指定的商品属性。';
        $res['err_no']  = 1;
    }
    else
    {
        if ($number == 0)
        {
            $res['qty'] = $number = 1;
        }
        else
        {
            $res['qty'] = $number;
        }

        $shop_price  = get_final_price($goods_id, $number, true, $attr_id);
        $res['result'] = price_format($shop_price * $number);
    }

    die($json->encode($res));
}

/*------------------------------------------------------ */
//-- 重新加载商品图片
/*------------------------------------------------------ */

if (!empty($_REQUEST['act']) && $_REQUEST['act'] == 'get_goods_pics')
{
    include('includes/cls_json.php');
	$json   = new JSON;
	$result    = array('err_msg' => '', 'content' => '', 'goods_id' => 0);
	
	$goods_id =  intval($_POST['g_id']);
	$color_id = intval($_POST['c_id']);
	
	$smarty->assign('goods_id', $goods_id);
	$smarty->assign('goods', get_goods_info($goods_id));

	$smarty->assign('pictures', get_goods_gallery($goods_id,$color_id));  // 商品相册
    $result['content']  = $smarty->fetch('library/goods_gallery.lbi');

    echo $json->encode($result);
    exit;
}

if(!empty($_GET['act']) && $_GET['act']=='set_goods_color_size'){
	
    include('includes/cls_json.php');

    $json   = new JSON;
    $res    = array('err_msg' => '', 'result' => '');

    $color_id = (isset($_GET['color_id'])) ? intval($_GET['color_id']) : 1;
    $goods_id = (isset($_GET['goods_id'])) ? intval($_GET['goods_id']) : 0;  
    if ($color_id == 0)
    {
        $res['err_msg'] = '颜色参数值丢失。';
        $res['err_no']  = 1;
    }
    else
    {
    	$sql = 'select s.* from '.$os->table('goods_inventory').' as gi,'.$os->table('size').' as s where gi.size_id = s.size_id and gi.color_id = '.$color_id.' and gi.goods_id = '.$goods_id.' order by s.size_name desc';
		$res = $db->getAll($sql);

		$str = '<ul id="s_m">';
		
		foreach ($res as $size) {
			$str .= '<li id="size_'.$size['size_id'].'" onClick="set_goods_size(this,'.$size['size_id'].',&quot;'.$size['size_name'].'&quot;)">'.$size['size_name'].'</li>';
		}
		
		$str .= '</ul>';
		
		$res['result'] = $str;
    }
    die($json->encode($res));	
}

if(!empty($_GET['act']) && $_GET['act']=='switch_color_img'){
	
    include('includes/cls_json.php');

    $json   = new JSON;
    $res    = array('err_msg' => '', 'result' => '');

    $color_id = (isset($_GET['color_id'])) ? intval($_GET['color_id']) : 1;
    $goods_id = (isset($_GET['goods_id'])) ? intval($_GET['goods_id']) : 0;  
    if ($color_id == 0)
    {
        $res['err_msg'] = '颜色参数值丢失。';
        $res['err_no']  = 1;
    }
    else
    {
    	$_gc_row=$db->getRow("SELECT gc.color_id,g.goods_id,g.goods_name FROM ".$os->table('goods_color')." gc LEFT JOIN ".
    				         $os->table('goods')." g ON gc.goods_id=g.goods_id WHERE gc.goods_id='$goods_id' AND ".
    				         " gc.color_id='$color_id' LIMIT 1");	         
    	if($_gc_row && $_gc_row['goods_id']>0){
    		$sql = "SELECT * FROM ".$os->table('goods_gallery')."  WHERE goods_id='$_gc_row[goods_id]' ".
        	                      " AND color_id='$_gc_row[color_id]' AND type=1 ORDER BY sort_order,img_id DESC";
        	$color_gg=$db->getAll($sql);

        	$list = array();
        	foreach ($color_gg as $val)
        	{
        		$val['img_original'] = $_CFG['pre_fetch_img'].$val['img_url'].'?296,370,1';
        		$val['thumb_url'] = $_CFG['pre_fetch_img'].$val['thumb_url'].'?37,47';
        		$val['img_url'] = $_CFG['pre_fetch_img'].$val['img_original'].'?37,47';
        		$list[] = $val;
        	}
        	
	        $res['result'] = array('list'=>$list,'goods_name'=>$_gc_row['goods_name']);
    	}else{
	        $res['err_msg'] = '颜色参数值丢失。';
	        $res['err_no']  = 1;    	    		
    	}
    }
    die($json->encode($res));	
}
if(!empty($_GET['act']) && $_GET['act']=='show_size_lib'){
    /* 取得参数：团购活动id */
    $lib_id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
    if ($lib_id <= 0)
    {
        os_header("Location: ./\n");
        exit;
    }

	$size_lib = $db->getRow("SELECT lib_id,lib_name,lib_desc FROM ".$os->table('size_lib')." WHERE lib_id='$lib_id'");
    if (empty($size_lib))
    {
        os_header("Location: ./\n");
        exit;
    }	
	$smarty->assign('size_lib',  $size_lib);
    $smarty->assign('helps',            get_shop_help()); // 网店帮助
	assign_template();
	$smarty->display('size_lib.dwt');    
	exit();
}

if(!empty($_GET['act']) && $_GET['act']=='view_goods_size_lib'){
    
    $goods_size_lib_id = isset($_REQUEST['lid']) ? intval($_REQUEST['lid']) : 0;

    if ($goods_size_lib_id <= 0)
    {
        os_header("Location: ./\n");
        exit;
    }

    $size_lib = $db->getRow("SELECT * FROM ".$os->table('size_lib')." WHERE lib_id=".$goods_size_lib_id);
    
	$smarty->assign('lib_name',  $size_lib['lib_name']); 
	$smarty->assign('lib_desc',  $size_lib['lib_desc']); 

	assign_template();
	$smarty->display('goods_size_lib.dwt');    
	exit();
}

// 商品展示页面查看商品库存
if(!empty($_GET['act']) && $_GET['act']=='view_inv'){
    
	/* 取得商品ID */
    $goods_id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
    
    if ($goods_id <= 0)
    {
        os_header("Location: ./\n");
        exit;
    }

    $goods_inventory_list = goods_inventory_list($goods_id);
    
	$smarty->assign('goods_name',  $goods_inventory_list['goods_name']); //商品名称
	$smarty->assign('size',  $goods_inventory_list['size']); //库存数量	
    $smarty->assign('goods_inventory_list',$goods_inventory_list['inventory_list']); // 商品库存清单
	assign_template();
	$smarty->display('goods_inventory.dwt');    
	exit();
}

/*------------------------------------------------------ */
//-- PROCESSOR
/*------------------------------------------------------ */

$cache_id = $goods_id . '-' . $_SESSION['user_rank'].'-'.$_CFG['lang'];
$cache_id = sprintf('%X', crc32($cache_id));

if (!$smarty->is_cached('goods.dwt', $cache_id))
{
	
    $smarty->assign('image_width',  $_CFG['image_width']);
    $smarty->assign('image_height', $_CFG['image_height']);
    $smarty->assign('helps',        get_shop_help()); // 网店帮助
    $smarty->assign('id',           $goods_id);
    $smarty->assign('type',         0);
    $smarty->assign('cfg',          $_CFG);
    $smarty->assign('promotion',    get_promotion_info($goods_id));//促销信息
    $smarty->assign('promotion_info', get_promotion_info());
	
    /* 获得商品的信息 */
    $goods = get_goods_info($goods_id);
    $goods_size_lib_id = $goods['size_lib_id'];
    if ($goods === false)
    {
    	
        /* 如果没有找到任何记录则跳回到首页 */
        os_header("Location: ./\n");
        exit;
    }
    else
    {
        if ($goods['brand_id'] > 0)
        {
            $goods['goods_brand_url'] = build_uri('brand', array('bid'=>$goods['brand_id']), $goods['goods_brand']);
        }

        $shop_price   = $goods['shop_price'];
        $linked_goods = get_linked_goods($goods_id);

        $goods['goods_style_name'] = add_style($goods['goods_name'], $goods['goods_name_style']);

        /* 购买该商品可以得到多少钱的红包 */
        if ($goods['bonus_type_id'] > 0)
        {
            $time = gmtime();
            $sql = "SELECT type_money FROM " . $os->table('bonus_type') .
                    " WHERE type_id = '$goods[bonus_type_id]' " .
                    " AND send_type = '" . SEND_BY_GOODS . "' " .
                    " AND send_start_date <= '$time'" .
                    " AND send_end_date >= '$time'";
            $goods['bonus_money'] = floatval($db->getOne($sql));
            if ($goods['bonus_money'] > 0)
            {
                $goods['bonus_money'] = price_format($goods['bonus_money']);
            }
        }
        $size_lib = array();
        if($goods['size_lib_id']>0){
        	$img_file = '<img src="'.$filesync_host.'/themes/default/images/detail/d_z.gif"/>';
        	$size_lib = $db->getRow("SELECT is_define,site_url FROM ".$os->table('size_lib')." WHERE lib_id=".intval($goods['size_lib_id']));
        	if(intval($size_lib['is_define']) == 1){
        		$js_code = "'./goods.php?act=view_goods_size_lib&lid=".$goods['size_lib_id']."'";
        		$size_lib_id_url = '<a href="javascript:goodsSizelib('.$js_code.')">'.$img_file.'</a>';
        	}else{
        		$size_lib_id_url = '<a href="'.$size_lib['site_url'].'" target="_blank">'.$img_file.'</a>';
        	}
        	$smarty->assign('size_lib_id_url',  $size_lib_id_url);
        }
        $goods_inventory_link = 'goods.php?act=view_inv&id='.$goods['goods_id'];
        $smarty->assign('goods',              		$goods);
        
        $smarty->assign('goods_size_lib_id',  		$goods_size_lib_id);
        $smarty->assign('goods_id',           		$goods['goods_id']);
        $smarty->assign('goods_inventory_link', 	$goods_inventory_link);
        $smarty->assign('promote_end_time',   		$goods['gmt_end_time']);

        $smarty->assign('categories',         get_categories_tree($goods['cat_id'],'goods_detail'));  // 分类树

        /* meta */
        $smarty->assign('keywords',           htmlspecialchars($goods['keywords']));
        $smarty->assign('description',        htmlspecialchars($goods['goods_brief']));


        $catlist = array();
        foreach(get_parent_cats($goods['cat_id']) as $k=>$v)
        {
            $catlist[] = $v['cat_id'];
        }

        assign_template('c', $catlist);

//         /* 上一个商品下一个商品 */
            $prev_gid = $db->getOne("SELECT max(goods_id) FROM " .$os->table('goods'). " WHERE cat_id=" . $goods['cat_id'] . " AND goods_id < " . $goods['goods_id'] . " AND is_on_sale = 1 AND is_alone_sale = 1 AND is_delete = 0 LIMIT 1");
        if (!empty($prev_gid))
        {
            $prev_good['url'] = build_uri('goods', array('gid' => $prev_gid));
            $smarty->assign('prev_good', $prev_good['url']);//上一个商品
        }

        $next_gid = $db->getOne("SELECT goods_id FROM " . $os->table('goods') . " WHERE cat_id=".$goods['cat_id']." AND goods_id > ".$goods['goods_id'] . " AND is_on_sale = 1 AND is_alone_sale = 1 AND is_delete = 0");
        if (!empty($next_gid))
        {
            $next_good['url'] = build_uri('goods', array('gid' => $next_gid));
            $smarty->assign('next_good', $next_good['url']);//下一个商品
        }

        $position = assign_ur_here($goods['cat_id'], $goods['goods_name']);

        /* current position */
        $smarty->assign('page_title',          $position['title']);                    // 页面标题
        $smarty->assign('ur_here',             $position['ur_here']);                  // 当前位置
        
 
        $goods_specs = get_goods_specs($goods_id);   //颜色和尺码规格
        $specs_color = sizeof($goods_specs['color'][0]);
        $specs_size  = sizeof($goods_specs['size'][0]);
        // 修改by贾军
        $color_flag = $specs_color > 1 ?'':'-1';
        $size_flag  = $specs_size  > 1 ?'':'-1';
        $smarty->assign('color_flag',$color_flag);              
        $smarty->assign('size_flag',$size_flag);

        $smarty->assign('goods_specs',$goods_specs);
        $goods_properties = get_goods_properties($goods_id);  // 获得商品的规格和属性

        $group_goods = get_group_goods($goods_id);
        $goods_gallery = get_goods_galleries($goods_id);
                
        $smarty->assign('comm_properties',          $goods_properties['pro']['商品属性']); // 商品属性


        $smarty->assign('specification',       $properties['spe']);                              // 商品规格
//      $smarty->assign('attribute_linked',    get_same_attribute_goods($properties));           // 相同属性的关联商品
        //$smarty->assign('related_goods',       $linked_goods);                                 // 关联商品
        $smarty->assign('group_goods',         $group_goods);
        $smarty->assign('goods_gallery',       $goods_gallery);                                  // 关联搭配

        $smarty->assign('goods_article_list',  get_linked_articles($goods_id));                  // 关联文章
        $smarty->assign('fittings',            get_goods_fittings(array($goods_id)));            // 配件
        $smarty->assign('rank_prices',         get_user_rank_prices($goods_id, $shop_price));    // 会员等级价格
		
        $smarty->assign('pictures',            get_goods_gallery($goods_id,$color_id));                    // 商品相册
        $smarty->assign('bought_goods',        get_also_bought($goods_id));                      // 购买了该商品的用户还购买了哪些商品
        $smarty->assign('goods_rank',          get_goods_rank($goods_id));                       // 商品的销售排名 
        //获取tag
        $tag_array = get_tags($goods_id);
        $smarty->assign('tags',                $tag_array);                                       // 商品的标记
        //获取关联tag
        $tag_data = "";
        foreach($tag_array as $temp_data)
        {
            $tag_data[] = $temp_data['tag_words'];
        }
        $tag_linked_data = user_uc_call('get_linked_tags', array($tag_data));
        $smarty->assign('tag_linked_data', $tag_linked_data);

        //获取关联礼包
        $package_goods_list = get_package_goods_list($goods['goods_id']);
        $smarty->assign('package_goods_list',$package_goods_list);    // 获取关联礼包

        assign_dynamic('goods');
        $volume_price_list = get_volume_price_list($goods['goods_id'], '1');
        $smarty->assign('volume_price_list',$volume_price_list);    // 商品优惠价格区间
		$smarty->assign('switch_color_img',$_CFG['switch_color_img']);
    }
}

/* 记录浏览历史 */
if (!empty($_COOKIE['OS']['history']))
{
    $history = explode(',', $_COOKIE['OS']['history']);

    array_unshift($history, $goods_id);
    $history = array_unique($history);

    while (count($history) > $_CFG['history_number'])
    {
        array_pop($history);
    }

    setcookie('OS[history]', implode(',', $history), gmtime() + 3600 * 24 * 30);
}
else
{
    setcookie('OS[history]', $goods_id, gmtime() + 3600 * 24 * 30);
}

/* 更新点击次数 */
$db->query('UPDATE ' . $os->table('goods') . " SET click_count = click_count + 1 WHERE goods_id = '$_REQUEST[id]'");

$smarty->assign('now_time',  gmtime());           // 当前系统时间

if (empty($_SESSION['user_id'])){
	$smarty->assign('user_id',      0);
}else{
	$smarty->assign('user_id',      1);
}

$buyer_show_list = get_buyershow_list($goods_id);

$smarty->assign('buyer_show_list',      $buyer_show_list);
$smarty->display('goods.dwt',      $cache_id);

/*------------------------------------------------------ */
//-- PRIVATE FUNCTION
/*------------------------------------------------------ */

function get_buyershow_list($goods_id){
	$sql = 'select * from '.$GLOBALS['os']->table('buyer_show').' where goods_id ='.$goods_id;
	$result = $GLOBALS['db']->getAll($sql);
	return $result;
}

function get_goods_galleries($goods_id){
	global $_CFG;
	$sql = "SELECT * FROM ".$GLOBALS['os']->table('goods_gallery')."  WHERE goods_id='$goods_id' ".
		   " ORDER BY sort_order,img_id DESC";
	$gallery = $GLOBALS['db']->getAll($sql);

	$list = array();
	foreach ($gallery as $val)
	{
		$val['img_original'] = $_CFG['pre_fetch_img'].$val['img_url'].'?320,370,1';
		$val['thumb_url'] = $_CFG['pre_fetch_img'].$val['thumb_url'].'?37,47';
		$val['img_url'] = $_CFG['pre_fetch_img'].$val['img_original'].'?37,47';
		$list[] = $val;
	}
	return $list;
}

function get_group_goods($goods_id){
	
	global $_CFG;
	$arr_group = array();
	$str = '';
	
	$sql = "select goods_id from ".$GLOBALS['os']->table('group_goods').' as gg where gg.parent_id = '.$goods_id;
	$res = $GLOBALS['db']->getAll($sql);
	
	if(!empty($res) && (sizeof($res) != 0)){
		foreach ($res AS $group_goods){
			array_push($arr_group,$group_goods['goods_id']);
		}
		$group_goods_ids = implode(',',$arr_group);


		$sql = 'SELECT g.goods_id,g.goods_name,g.shop_price,g.original_img FROM '.$GLOBALS['os']->table('goods') ." as g WHERE g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND goods_id in (".$group_goods_ids.")";
		
		$res = $GLOBALS['db']->getAll($sql);

		foreach ($res AS $val)
		{
			$goods_name = htmlspecialchars($val['goods_name']);
			$original_img = $val['original_img'];
			$shop_price = $val['shop_price'];

			if ($goods_name)
			{
				$short_name = $GLOBALS['_CFG']['goods_name_length'] > 0 ? sub_str($goods_name, $GLOBALS['_CFG']['goods_name_length']) : $goods_name;
				$url = build_uri('goods', array('gid' => $val['goods_id']), $goods_name);
				$str .='<li><table cellpadding="0" cellspacing="0" border="0" align="center" ><tr><td valign="middle"  class="dt_img_w"><a href="'.$url.'" title="' . $goods_name . '"><img src="'.$_CFG['pre_fetch_img'].$original_img.'?70,88" alt="'.$goods_name.'"/></a>
		                </td></tr><tr><td><div >￥'.$shop_price.'</a></div>
		                </td></tr></table></li>';
			}
		}
	}
	
	return $str;
}

/**
 * 获得指定商品的关联商品
 *
 * @access  public
 * @param   integer     $goods_id
 * @return  array
 */
function get_linked_goods($goods_id)
{
    $sql = 'SELECT g.goods_id, g.goods_name, g.goods_thumb, g.goods_img, g.shop_price AS org_price, ' .
                "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, ".
                'g.market_price, g.promote_price, g.promote_start_date, g.promote_end_date ' .
            'FROM ' . $GLOBALS['os']->table('link_goods') . ' lg ' .
            'LEFT JOIN ' . $GLOBALS['os']->table('goods') . ' AS g ON g.goods_id = lg.link_goods_id ' .
            "LEFT JOIN " . $GLOBALS['os']->table('member_price') . " AS mp ".
                    "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ".
            "WHERE lg.goods_id = '$goods_id' AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 ".
            "LIMIT " . $GLOBALS['_CFG']['related_goods_number'];
    $res = $GLOBALS['db']->query($sql);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $arr[$row['goods_id']]['goods_id']     = $row['goods_id'];
        $arr[$row['goods_id']]['goods_name']   = $row['goods_name'];
        $arr[$row['goods_id']]['short_name']   = $GLOBALS['_CFG']['goods_name_length'] > 0 ?
            sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name'];
        $arr[$row['goods_id']]['goods_thumb']  = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $arr[$row['goods_id']]['goods_img']    = get_image_path($row['goods_id'], $row['goods_img']);
        $arr[$row['goods_id']]['market_price'] = price_format($row['market_price']);
        $arr[$row['goods_id']]['shop_price']   = price_format($row['shop_price']);
        $arr[$row['goods_id']]['url']          = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']);

        if ($row['promote_price'] > 0)
        {
            $arr[$row['goods_id']]['promote_price'] = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
            $arr[$row['goods_id']]['formated_promote_price'] = price_format($arr[$row['goods_id']]['promote_price']);
        }
        else
        {
            $arr[$row['goods_id']]['promote_price'] = 0;
        }
    }

    return $arr;
}

/**
 * 获得指定商品的关联文章
 *
 * @access  public
 * @param   integer     $goods_id
 * @return  void
 */
function get_linked_articles($goods_id)
{
    $sql = 'SELECT a.article_id, a.title, a.file_url, a.open_type, a.add_time ' .
            'FROM ' . $GLOBALS['os']->table('goods_article') . ' AS g, ' .
                $GLOBALS['os']->table('article') . ' AS a ' .
            "WHERE g.article_id = a.article_id AND g.goods_id = '$goods_id' AND a.is_open = 1 " .
            'ORDER BY a.add_time DESC';
    $res = $GLOBALS['db']->query($sql);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $row['url']         = $row['open_type'] != 1 ?
            build_uri('article', array('aid'=>$row['article_id']), $row['title']) : trim($row['file_url']);
        $row['add_time']    = local_date($GLOBALS['_CFG']['date_format'], $row['add_time']);
        $row['short_title'] = $GLOBALS['_CFG']['article_title_length'] > 0 ?
            sub_str($row['title'], $GLOBALS['_CFG']['article_title_length']) : $row['title'];

        $arr[] = $row;
    }

    return $arr;
}

/**
 * 获得指定商品的各会员等级对应的价格
 *
 * @access  public
 * @param   integer     $goods_id
 * @return  array
 */
function get_user_rank_prices($goods_id, $shop_price)
{
    $sql = "SELECT rank_id, IFNULL(mp.user_price, r.discount * $shop_price / 100) AS price, r.rank_name, r.discount " .
            'FROM ' . $GLOBALS['os']->table('user_rank') . ' AS r ' .
            'LEFT JOIN ' . $GLOBALS['os']->table('member_price') . " AS mp ".
                "ON mp.goods_id = '$goods_id' AND mp.user_rank = r.rank_id " .
            "WHERE r.show_price = 1 OR r.rank_id = '$_SESSION[user_rank]'";
    $res = $GLOBALS['db']->query($sql);

    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {

        $arr[$row['rank_id']] = array(
                        'rank_name' => htmlspecialchars($row['rank_name']),
                        'price'     => price_format($row['price']));
    }

    return $arr;
}

/**
 * 获得购买过该商品的人还买过的商品
 *
 * @access  public
 * @param   integer     $goods_id
 * @return  array
 */
function get_also_bought($goods_id)
{
    $sql = 'SELECT COUNT(b.goods_id ) AS num, g.goods_id, g.goods_name, g.goods_thumb, g.goods_img, g.shop_price, g.promote_price, g.promote_start_date, g.promote_end_date ' .
            'FROM ' . $GLOBALS['os']->table('order_goods') . ' AS a ' .
            'LEFT JOIN ' . $GLOBALS['os']->table('order_goods') . ' AS b ON b.order_id = a.order_id ' .
            'LEFT JOIN ' . $GLOBALS['os']->table('goods') . ' AS g ON g.goods_id = b.goods_id ' .
            "WHERE a.goods_id = '$goods_id' AND b.goods_id <> '$goods_id' AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 " .
            'GROUP BY b.goods_id ' .
            'ORDER BY num DESC ' .
            'LIMIT ' . $GLOBALS['_CFG']['bought_goods'];
    $res = $GLOBALS['db']->query($sql);

    $key = 0;
    $arr = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $arr[$key]['goods_id']    = $row['goods_id'];
        $arr[$key]['goods_name']  = $row['goods_name'];
        $arr[$key]['short_name']  = $GLOBALS['_CFG']['goods_name_length'] > 0 ?
            sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name'];
        $arr[$key]['goods_thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $arr[$key]['goods_img']   = get_image_path($row['goods_id'], $row['goods_img']);
        $arr[$key]['shop_price']  = price_format($row['shop_price']);
        $arr[$key]['url']         = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']);

        if ($row['promote_price'] > 0)
        {
            $arr[$key]['promote_price'] = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
            $arr[$key]['formated_promote_price'] = price_format($arr[$key]['promote_price']);
        }
        else
        {
            $arr[$key]['promote_price'] = 0;
        }

        $key++;
    }

    return $arr;
}

/**
 * 获得指定商品的销售排名
 *
 * @access  public
 * @param   integer     $goods_id
 * @return  integer
 */
function get_goods_rank($goods_id)
{
    /* 统计时间段 */
    $period = intval($GLOBALS['_CFG']['top10_time']);
    if ($period == 1) // 一年
    {
        $ext = " AND o.add_time > '" . local_strtotime('-1 years') . "'";
    }
    elseif ($period == 2) // 半年
    {
        $ext = " AND o.add_time > '" . local_strtotime('-6 months') . "'";
    }
    elseif ($period == 3) // 三个月
    {
        $ext = " AND o.add_time > '" . local_strtotime('-3 months') . "'";
    }
    elseif ($period == 4) // 一个月
    {
        $ext = " AND o.add_time > '" . local_strtotime('-1 months') . "'";
    }
    else
    {
        $ext = '';
    }

    /* 查询该商品销量 */
    $sql = 'SELECT IFNULL(SUM(g.goods_number), 0) ' .
        'FROM ' . $GLOBALS['os']->table('order_info') . ' AS o, ' .
            $GLOBALS['os']->table('order_goods') . ' AS g ' .
        "WHERE o.order_id = g.order_id " .
        "AND o.order_status = '" . OS_CONFIRMED . "' " .
        "AND o.shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) .
        " AND o.pay_status " . db_create_in(array(PS_PAYED, PS_PAYING)) .
        " AND g.goods_id = '$goods_id'" . $ext;
    $sales_count = $GLOBALS['db']->getOne($sql);

    if ($sales_count > 0)
    {
        /* 只有在商品销售量大于0时才去计算该商品的排行 */
        $sql = 'SELECT DISTINCT SUM(goods_number) AS num ' .
                'FROM ' . $GLOBALS['os']->table('order_info') . ' AS o, ' .
                    $GLOBALS['os']->table('order_goods') . ' AS g ' .
                "WHERE o.order_id = g.order_id " .
                "AND o.order_status = '" . OS_CONFIRMED . "' " .
                "AND o.shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) .
                " AND o.pay_status " . db_create_in(array(PS_PAYED, PS_PAYING)) . $ext .
                " GROUP BY g.goods_id HAVING num > $sales_count";
        $res = $GLOBALS['db']->query($sql);

        $rank = $GLOBALS['db']->num_rows($res) + 1;

        if ($rank > 10)
        {
            $rank = 0;
        }
    }
    else
    {
        $rank = 0;
    }

    return $rank;
}

/**
 * 获得商品选定的属性的附加总价格
 *
 * @param   integer     $goods_id
 * @param   array       $attr
 *
 * @return  void
 */
function get_attr_amount($goods_id, $attr)
{
    $sql = "SELECT SUM(attr_price) FROM " . $GLOBALS['os']->table('goods_attr') .
        " WHERE goods_id='$goods_id' AND " . db_create_in($attr, 'goods_attr_id');

    return $GLOBALS['db']->getOne($sql);
}

/**
 * 取得跟商品关联的礼包列表
 *
 * @param   string  $goods_id    商品编号
 *
 * @return  礼包列表
 */
function get_package_goods_list($goods_id)
{
    $now = gmtime();
    $sql = "SELECT ga.act_id, ga.act_name, ga.act_desc, ga.goods_id, ga.goods_name, ga.start_time, ".
           " ga.end_time, ga.is_finished, ga.ext_info ".
           " FROM " . $GLOBALS['os']->table('goods_activity') . " AS ga".
           " WHERE ga.goods_id = " . $goods_id ." AND ga.act_type = " . GAT_PACKAGE .
           " AND start_time <= '" . $now . "' AND end_time >= '" . $now . "' ".
           " ORDER BY ga.act_id";

    $res = $GLOBALS['db']->getAll($sql);

    foreach ($res as $tempkey => $value)
    {
        $subtotal = 0;
        $row = unserialize($value['ext_info']);
        unset($value['ext_info']);
        if ($row)
        {
            foreach ($row as $key=>$val)
            {
                $res[$tempkey][$key] = $val;
            }
        }

        $sql = "SELECT pg.package_id, pg.goods_id, pg.goods_number, pg.admin_id, ".
               " g.goods_sn, g.goods_name, g.market_price, g.goods_thumb, ".
               " IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS rank_price " .
               " FROM " . $GLOBALS['os']->table('package_goods') . " AS pg ".
               "   LEFT JOIN ". $GLOBALS['os']->table('goods') . " AS g ".
               "   ON g.goods_id = pg.goods_id ".
               " LEFT JOIN " . $GLOBALS['os']->table('member_price') . " AS mp ".
                    "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ".
               " WHERE pg.package_id = " . $value['act_id']. " ".
               " ORDER BY pg.package_id, pg.goods_id";

        $goods_res = $GLOBALS['db']->getAll($sql);

        foreach($goods_res as $key => $val)
        {
            $goods_res[$key]['goods_thumb']  = get_image_path($val['goods_id'], $val['goods_thumb'], true);
            $goods_res[$key]['market_price'] = price_format($val['market_price']);
            $goods_res[$key]['rank_price']   = price_format($val['rank_price']);
            $subtotal += $val['rank_price'] * $val['goods_number'];
        }


        $res[$tempkey]['goods_list']    = $goods_res;
        $res[$tempkey]['subtotal']      = price_format($subtotal);
        $res[$tempkey]['saving']        = price_format(($subtotal - $res[$tempkey]['package_price']));
        $res[$tempkey]['package_price'] = price_format($res[$tempkey]['package_price']);
    }

    return $res;
}

/**
 *  返回给定商品库存信息数据
 *
 * @access  public
 * @param
 *
 * @return void
 */
function goods_inventory_list($goods_id){
	$goods_color_size_list = array();$goods_inventory_list = array();$inventory_list_temp = array();$inventory_array == ''
;$inventory_list = array();$goods_all_inventory_list = array();
	// 取出特定商品ID,商品名称以及其所有尺码、颜色,色块图片组合,并初始化所有库存量为0
	$sql_goods_color_size = 'select s.goods_id,g.goods_name,s.size_id,s.size_name,c.*,"0" as goods_number_actual,"0" as goods_number_available,"0" as goods_number_alert from '.$GLOBALS['os']->table('goods_size').' as s,'.$GLOBALS['os']->table('goods_color').' as c,'.$GLOBALS['os']->table('goods').' as g where g.goods_id = s.goods_id and s.goods_id = '.$goods_id.' and c.goods_id = '.$goods_id.' order by c.color_id asc,s.size_id asc';
	$goods_color_size_list = $GLOBALS['db']->getAll($sql_goods_color_size);

    // 取出特定商品的相应库存量
    $sql_goods_inventory = 'select i.size_id,i.color_id,i.goods_number_actual,i.goods_number_available,i.goods_number_alert from '.$GLOBALS['os']->table('goods_inventory').' as i where i.goods_id = '.$goods_id.' order by i.id asc';
    $goods_inventory_list = $GLOBALS['db']->getAll($sql_goods_inventory);

    // 整合商品库存数据
	foreach ($goods_color_size_list AS $key => $value){
	   	$item_1 = $value;
		foreach ($goods_inventory_list AS $key => $value){
			$item_2 = $value;
			if($item_1['size_id'] == $item_2['size_id'] && $item_1['color_id'] == $item_2['color_id']){
				$item_1['goods_number_actual'] = $item_2['goods_number_actual'];
				$item_1['goods_number_available'] = $item_2['goods_number_available'];
				$item_1['goods_number_alert'] = $item_2['goods_number_alert'];
			}
		}
		
        $img_item = '<a href="../' . DATA_DIR . '/color_img/'.$item_1['img_file'].'" target="_brank">
                     <img src="../' . DATA_DIR . '/color_img/'.$item_1['img_file'].'" width="40" height="40" border="0" alt="'.$item_1['img_name'].'"/></a>';
        $item_1['img_item'] = $img_item;
		array_push($inventory_list_temp,$item_1);
	}
	
	$size = count($inventory_list_temp);
	$name = $inventory_list_temp[0]['goods_name'];
	
    // 用库存列表中的第一条记录的色块名称来初始化商品ID
    $id_init = $inventory_list_temp[0]['color_name'];
    
     // 根据商品色块归类,并使用商品色块ID做索引,重新整合库存列表
    foreach ($inventory_list_temp AS $inv_key => $inventory) {
    	$color_name = $inventory['color_name'];
    	// 如果是同一色块
    	// 就用该色块的名称做key,所有该商品的库存记录组成的数组做value
    	// 重新整合库存列表
    	if ($id_init == $color_name) {
    		if($inventory_array == ''){
    			$inventory_array = array();
    		}
    		$color_name = $inventory['color_name'];
    		array_push($inventory_array,$inventory);
    	}else{
    		$id_init = $color_name;
    		$inventory_list['invt'] = $inventory_array;
    		$inventory_list['size'] = count($inventory_array); 
			array_push($goods_all_inventory_list,$inventory_list);    		    			
    		$inventory_array = array();
    		$color_name = $inventory['color_name'];
    		array_push($inventory_array,$inventory);
    	}
  		if($inv_key + 1 == sizeof($inventory_list_temp)){
  			$inventory_list['invt'] = $inventory_array;
    		$inventory_list['size'] = count($inventory_array);  			
			array_push($goods_all_inventory_list,$inventory_list);    		    			    		
   		}
    }
    $arr = array(
    			'goods_name' => $name,
                'size' => $size,
                'inventory_list' => $goods_all_inventory_list
                );
    return $arr;
}

?>